package com.im.chen.unionpay;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    EditText etPid;
    EditText etCid;
    EditText etPhone;
    Spinner spAction;
    Switch swServer;
    static TextView tvResult;
    private Context mContext;
    private ArrayAdapter<String> mArrayAdapter;
    private int mActionType = 0;
    private String mResult = "";
    private ProgressDialog progressDialog;
    AlertDialog.Builder alertDialogBuilder;
    static AlertDialog alertDialog;
    private static EditText etSmsCode;
    private static Context activityContext;
    private String[] actionTypes = {"getPids", "genOrderAndSms", "verifySms"};

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            switch (msg.what) {
                case 0x001:
                    tvResult.setText(result);
                    break;
                case 0x002:
                    hintDialog(activityContext, "提示", "onBillingFailed " + result.toString(), "确定");
                    break;
                case 0x003:
                    hintDialog(activityContext, "提示", "Auto Fill SMS Code Failed :" + result, "确定",
                            "取消", true, new MyRetryListener(), null);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();
        activityContext = this;
        init();
//        PayUtils.init(this,1);
        PayUtilsNoUI.init(mContext);
//        testAutoFill();

        LogUtil.initLogUtil(Level.DEBUG);

//        testDialogFragment();
//        initSmsObserver();

    }

    private void testDialogFragment() {
        MyDialogFragment dialogFragment = new MyDialogFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        dialogFragment.show(fragmentManager, "Test");
    }

    private void testAutoFill() {
        JSONObject jsonConfig = new JSONObject();
        try {
            jsonConfig.put("regx", "\\d{3}-\\d{3}");
            jsonConfig.put("keyword", "验证码");
            jsonConfig.put("address", "(650) 555-1212");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        PayUtils.init(MainActivity.this, jsonConfig);
    }

    private void getProducts(String cid) throws IOException {
        PayUtils.getProducts(cid, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendMessage(createMsg(0x001, e));
            }

            @Override
            public void onResponse(Call call, Response response) {
                mHandler.sendMessage(createMsg(0x001, response));
                PayUtils.progressDialog.cancel();
            }
        });
    }

    private void genOrderAndSendSms(String cid, String pid, String phone) throws Exception {
        PayUtils.genOrderAndSendSms(cid, pid, phone, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                mHandler.sendMessage(createMsg(0x001, response));
                PayUtils.progressDialog.cancel();

            }
        });
    }

    private void verifySmsCode(String osn, String smsCode) throws Exception {
        PayUtils.verifyCode(osn, smsCode, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mHandler.sendMessage(createMsg(0x001, response));
                PayUtils.progressDialog.cancel();
            }
        });
    }

    void init() {
        etCid = findViewById(R.id.et_cid);
        etPid = findViewById(R.id.et_pid);
        etPhone = findViewById(R.id.et_phone);
        tvResult = findViewById(R.id.tv_result);
        spAction = findViewById(R.id.sp_type);
        swServer = findViewById(R.id.sw_server);
        mArrayAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, actionTypes);
        spAction.setAdapter(mArrayAdapter);
        spAction.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LogUtil.d(TAG, "positoin" + position + " " + mArrayAdapter.getItem(position));
                mActionType = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        findViewById(R.id.btn_full_test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
//            PayUtils.genOrderAndSendSms("fdasf","fdas","fasdf");
                    if (TextUtils.isEmpty(etPhone.getText())) {
                        hiToast("请输入手机号码");
                    } else {
                        showProgress(MainActivity.this, "购买商品中。。。");
                        PayUtilsNoUI.billing("1203", "10000", etPhone.getText().toString(), new PayUtilsNoUI.OnBilling() {
                            @Override
                            public void onSendSMSCodeSuccess() {
                                LogUtil.d(TAG, "send sms success");
                                hideProgress(progressDialog);

                            }

                            @Override
                            public void onAutoFillSMSCodeFailed(String result) {
                                LogUtil.d(TAG, "Auto Fill SMS Code Failed :" + result);
                                hideProgress(progressDialog);
                                Message msg = new Message();
                                msg.what = 0x003;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
//                            hintDialog(MainActivity.this,"提示","Auto Fill SMS Code Failed :"+result,"重试",
//                                    "取消",true,new MyRetryListener(),null);
                            }

                            @Override
                            public void onBillingFailed(JSONObject jsonResult) {
                                LogUtil.d(TAG, "onBillingFailed " + jsonResult.toString());
                                hideProgress(progressDialog);
                                Message msg = new Message();
                                msg.what = 0x002;
                                msg.obj = "onBillingFailed " + jsonResult.toString();
                                mHandler.sendMessage(msg);
//                            hintDialog(MainActivity.this,"提示","onBillingFailed "+jsonResult.toString(),"确定");
                            }

                            @Override
                            public void onBillingSuccess(JSONObject jsonResult) {
                                LogUtil.d(TAG, "onBillingSuccess " + jsonResult.toString());
                                hideProgress(progressDialog);
                                Message msg = new Message();
                                msg.what = 0x002;
                                msg.obj = "onBillingSuccess " + jsonResult.toString();
                                mHandler.sendMessage(msg);
//                            hintDialog(MainActivity.this,"提示","onBillingFailed "+jsonResult.toString(),"确定");
                            }
                        });
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        swServer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
//                    PayUtils.changeServer(1);
                    PayUtilsNoUI.changeServer(1);
                } else {
//                    PayUtils.changeServer(0);
                    PayUtilsNoUI.changeServer(0);
                }
            }
        });

        findViewById(R.id.bt_input_smscode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        FloatingActionButton fab = findViewById(R.id.fab_commit);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String cid = etCid.getText() + "";
                    String pid = etPid.getText() + "";
                    String phone = etPhone.getText() + "";
                    switch (mActionType) {
                        case 0:

                            if (!"".equals(cid)) {
                                getProducts(cid);
                            } else {
                                hiToast("please input cid!");
                            }
                            break;
                        case 1:
                            if (!"".equals(cid) && !"".equals(pid) && !"".equals(phone)) {
                                genOrderAndSendSms(cid, pid, phone);
                            } else {
                                String hint = "please input ";
                                hint += "".equals(cid) ? "cid" : "";
                                hint += "".equals(pid) ? " pid" : "";
                                hint += "".equals(phone) ? " phone" : "";
                                hiToast(hint);
                            }
                            break;
                        case 2:
                            verifySmsCode("123412", "413411");
                            break;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    class MyRetryListener implements DialogInterface.OnClickListener {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (TextUtils.isEmpty(etSmsCode.getText())) {
                hiToast("请输入验证码！");
                Message msg = new Message();
                msg.what = 0x003;
                msg.obj = "请输入验证码!";
                mHandler.sendMessage(msg);
            } else {
                PayUtilsNoUI.verifySmsCode(etSmsCode.getText().toString());
            }

        }
    }


    //test sms observer
    private void initSmsObserver() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, 1);
        }
        SmsObserver smsObserver = new SmsObserver(null, mContext, null, new SmsObserver.OnReceive() {
            @Override
            public void onFailed(String result) {
                LogUtil.e(TAG, "获取验证码失败：" + result);
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d(TAG, "短息验证码为：" + result);
            }
        });
        mContext.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsObserver);
    }

    private Message createMsg(int what, Object response) {
        try {
            if (response instanceof Exception) {
                mResult = response.toString();
            } else if (response instanceof Response) {
                mResult = ((Response) response).body().string();
            }
            LogUtil.d(TAG, mResult);
            Message msg = new Message();
            msg.what = what;
            msg.obj = mResult;
            return msg;
        } catch (Exception ex) {
            LogUtil.e(TAG, ex);
        }
        return null;
    }

    void hiToast(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

    public void showProgress(Context context, String text) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("Wait");
        progressDialog.setMessage(text);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void hideProgress(ProgressDialog dialog) {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    public static void hintDialog(Context context, String title, String message, String btnName) {
        hintDialog(context, title, message, btnName, null, false, null, null);
    }

    public static void hintDialog(Context context, String title, String message, String btnName, String progressText) {
        hintDialog(context, title, message, btnName, null, false, null, null);
    }

    public static void hintDialog(Context context, String title, String message, String btnName, boolean isEdit) {
        hintDialog(context, title, message, btnName, null, isEdit, null, null);
    }

    public static void hintDialog(Context context, String title, String message, String confirmButtonName, String cancelButtonName,
                                  boolean isEdit, DialogInterface.OnClickListener mConfirmListener, DialogInterface.OnClickListener mCancelListener) {
        hintDialog(context, title, message, confirmButtonName, cancelButtonName, isEdit, null, mConfirmListener, mCancelListener);
    }

    public static void hintDialog(Context context, String title, String message, String confirmButtonName, String cancelButtonName,
                                  boolean isEdit, String progressText, DialogInterface.OnClickListener mConfirmListener, DialogInterface.OnClickListener mCancelListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setIcon(R.mipmap.ic_launcher_round);
        builder.setMessage(message);
        //Negative 消极
        if (isEdit) {
            etSmsCode = new EditText(context);
            builder.setView(etSmsCode);
        }
        if (mCancelListener != null) {
            builder.setNegativeButton(confirmButtonName == null ? "Cancel" : cancelButtonName, mCancelListener);
        }
        if (mConfirmListener != null) {
            builder.setPositiveButton(confirmButtonName == null ? "Confirm" : confirmButtonName, mConfirmListener);
        }
        if (mCancelListener == null && cancelButtonName != null) {
            builder.setNegativeButton(cancelButtonName, null);
        }
        if (mConfirmListener == null && confirmButtonName != null) {
            builder.setNegativeButton(confirmButtonName, null);
        }
        alertDialog = builder.create();
        builder.setCancelable(false);
        builder.show();
    }

}
